<template>
  <div class="page-wapper">
    <!-- 机构管理 -->
    <div class="container">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">机构名称：</div>
            <el-input
              v-model="filterData.orgName"
              size="small"
              placeholder="请输入"
              clearable
            ></el-input>
          </div>

          <div class="filter_item">
            <div class="label">机构状态：</div>
            <el-select
              v-model="filterData.orgStatus"
              placeholder="请选择"
              size="small"
              clearable
            >
              <el-option
                v-for="item in prepareData.orgStatusSelectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <div class="filter_item">
            <div class="label">是否可加入：</div>
            <el-select
              v-model="filterData.canJoin"
              placeholder="请选择"
              size="small"
              clearable
            >
              <el-option
                v-for="item in prepareData.canJoinSelectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>

          <!-- <div class="filter_item">
            <div class="label">机构管理员：</div>
            <el-select
              v-model="filterData.orgManagerId"
              placeholder="请选择"
              size="small"
              clearable
            >
              <el-option
                v-for="item in prepareData.canJoinSelectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div> -->
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              size="mini"
              :loading="searchBtnLoading"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_options_bar">
        <!-- 标签筛选列 -->
        <el-popover placement="bottom-start" trigger="click" width="600px">
          <div style="display: flex; flex-wrap: wrap">
            <div style="width: 200px">
              <el-checkbox
                v-model="columnsAll.visible"
                @change="tagCheckedChange(columnsAll)"
                >全选
              </el-checkbox>
            </div>
            <template v-for="(item, i) in columns">
              <div v-if="item.title" :key="i" style="width: 200px">
                <el-checkbox
                  v-model="item.visible"
                  :disabled="disabledCancleColumns.includes(item.title)"
                  @change="tagCheckedChange(item)"
                  >{{ item.title }}
                </el-checkbox>
              </div>
            </template>
          </div>

          <template #reference>
            <el-button type="primary" size="mini">筛选列</el-button>
          </template>
        </el-popover>
        <div>
          <el-button
            v-if="$hasPermission($permission.ORG_SAVE_OR_UPDATE)"
            size="mini"
            type="primary"
            @click="handleCreate"
          >
            新建
          </el-button>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          :menu-config="{}"
          :checkbox-config="{ checkField: 'checked', trigger: 'row' }"
          :row-config="{ height: 100 }"
          :row-style="rowStyle"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          show-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
        >
          <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>

          <vxe-column
            type="seq"
            title="序号"
            width="60"
            fixed="left"
          ></vxe-column>
          <TableColum :colums="tableColum">
            <template #avatar="{ props }">
              <div style="text-align: center">
                <div v-if="props.row.avatarUrl" @click.stop="" class="d_f j_c">
                  <el-image
                    style="width: 80px; height: 80px; border-radius: 50%"
                    :src="props.row.avatarUrl"
                    :preview-src-list="[props.row.avatarUrl]"
                    lazy
                  ></el-image>
                </div>
                <span v-else>无</span>
              </div>
            </template>
          </TableColum>
          <vxe-column #default="{ row }" width="200" title="操作" fixed="right">
            <div>
              <el-button
                v-if="$hasPermission($permission.ORG_SAVE_OR_UPDATE)"
                size="mini"
                type="text"
                @click.stop="handleEdit(row)"
              >
                编辑
              </el-button>

              <el-button
                v-if="
                  row.canJoin === '1' &&
                  $hasPermission($permission.ORG_SET_CAN_JOIN)
                "
                size="mini"
                type="text"
                style="color: #e6a23c"
                @click.stop="handleJoin(row, '0')"
              >
                不可加入
              </el-button>

              <el-button
                v-else-if="
                  row.canJoin === '0' &&
                  $hasPermission($permission.ORG_SET_CAN_JOIN)
                "
                size="mini"
                type="text"
                style="color: #67c23a"
                @click.stop="handleJoin(row, '1')"
              >
                可加入
              </el-button>

              <el-button
                v-if="
                  row.orgStatus === '1' &&
                  $hasPermission($permission.ORG_SET_STATUS)
                "
                size="mini"
                type="text"
                style="color: #e6a23c"
                @click.stop="handleStop(row, true)"
              >
                停用
              </el-button>

              <el-button
                v-else-if="
                  row.orgStatus === '0' &&
                  $hasPermission($permission.ORG_SET_STATUS)
                "
                size="mini"
                type="text"
                style="color: #67c23a"
                @click.stop="handleStop(row, false)"
              >
                启用
              </el-button>

              <el-button
                v-if="$hasPermission($permission.ORG_DELETE)"
                size="mini"
                type="text"
                style="color: #f56c6c"
                @click.stop="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-sizes="[500, 100, 50, 15]"
        :page-size="pagenationData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>

    <!-- 编辑弹框 -->
    <OrgFormDialog
      ref="orgFormDialogRef"
      :prepareData="prepareData"
      @updateSuccess="getTableData"
    />
  </div>
</template>

<script>
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  getCurrentInstance,
  onActivated,
  toRefs,
} from "vue";
import OrgFormDialog from "./components/OrgFormDialog.vue";
import TableColum from "../../components/TabelTemplate/TableColum.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { dealImgUrl } from "../../utils/common";

const initFilterData = () => {
  return {
    orgName: null,
    orgStatus: null,
    canJoin: null,
    orgManagerId: null,
  };
};

export default {
  name: "OrgManage",
  components: { OrgFormDialog, TableColum },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;

    const orgFormDialogRef = ref(null);

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});
    const searchBtnLoading = ref(false);

    // 预加载数据
    const prepareData = reactive({
      orgStatusSelectList: [],
      canJoinSelectList: [],
      isOpenVerificationSelectList: [],
    });

    const tableState = reactive({
      columnsAll: {
        visible: true,
        title: "全选",
      },
      // 标签筛选列
      columns: [],
      // 列表标签筛选需要禁用筛选的选项
      disabledCancleColumns: ["序号", "操作"],
      xTable: null,
      tableData: [],
      tableLoading: false,
      tableColum: {
        orgName: {
          title: "机构名称",
          props: { sortable: false },
        },
        orgAvatar: {
          title: "机构logo",
          props: { sortable: false },
          slotContent: "avatar",
        },
        orgStatusLabel: {
          title: "机构状态",
          props: { sortable: false },
        },
        memberCount: {
          title: "机构人数",
          props: { sortable: false },
        },
        canJoinLabel: {
          title: "是否可加入",
          props: { sortable: false },
        },
        orgDesc: {
          title: "机构描述",
          props: { sortable: false },
        },
        orgManagerName: {
          title: "机构管理员",
          props: { sortable: false },
        },
        creatorName: {
          title: "创建人",
          props: { sortable: false },
        },
        createdTime: {
          title: "创建时间",
          props: { sortable: false, width: 160 },
        },
      },
    });

    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableState.tableLoading = true;
      $api.organization
        .listPage({
          ...pagenationData,
          condition,
        })
        .then((res) => {
          tableState.tableLoading = false;
          tableState.tableData = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
              avatarUrl: dealImgUrl(item.orgAvatar),
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableState.tableLoading = false;
          console.error("tableData error: ", err);
        });
    };

    // 新建
    const handleCreate = () => {
      nextTick(() => {
        orgFormDialogRef.value.open();
      });
    };

    // 编辑
    const handleEdit = (row) => {
      nextTick(() => {
        orgFormDialogRef.value.open(row);
      });
    };

    // 删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除【${
          row.orgName.length > 10
            ? row.orgName.slice(0, 10) + "..."
            : row.orgName
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          removeByIds([row.id]);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const removeByIds = (ids) => {
      tableState.tableLoading = true;
      $api.organization
        .removeByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("removeByIds error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 不可加入/可加入
    const handleJoin = (row, canJoin) => {
      ElMessageBox.confirm(
        `确定要设置【${
          row.orgName.length > 10
            ? row.orgName.slice(0, 10) + "..."
            : row.orgName
        }】为${canJoin === "0" ? "不可加入" : "可加入"}吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          setCanJoin(row.id, canJoin);
        })
        .catch(() => {});
    };

    // 设置机构是否可加入接口
    const setCanJoin = (orgId, canJoin) => {
      tableState.tableLoading = true;
      $api.organization
        .setCanJoin({
          orgId,
          canJoin,
        })
        .then((res) => {
          ElMessage.success("操作成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("setCanJoin error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 停用/启用
    const handleStop = (row, isStop) => {
      ElMessageBox.confirm(
        `确定要${isStop ? "停用" : "启用"}【${
          row.orgName.length > 10
            ? row.orgName.slice(0, 10) + "..."
            : row.orgName
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          setStatus(row.id, isStop);
        })
        .catch(() => {});
    };

    // 修改机构停用状态接口
    const setStatus = (orgId, isStop) => {
      tableState.tableLoading = true;
      $api.organization
        .setStatus({
          orgId,
          orgStatus: isStop ? "0" : "1",
        })
        .then((res) => {
          ElMessage.success("操作成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("setStatus error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 查询预加载数据
    const getPreparedData = () => {
      $api.organization
        .preparedData()
        .then((res) => {
          Object.keys(prepareData).forEach((key) => {
            prepareData[key] = res.data[key] || [];
          });
        })
        .catch((err) => {
          console.error("getPreparedData error: ", err);
        })
        .finally(() => {});
    };

    // 筛选列-全选按钮
    const tagCheckedChange = (item) => {
      if (item.title === "全选") {
        // 点击全选操作
        tableState.columns.forEach((cell) => {
          cell.visible = item.visible;
          if (
            !item.visible &&
            tableState.disabledCancleColumns.includes(cell.title)
          ) {
            cell.visible = !item.visible;
          }
        });
      }
      tableState.columnsAll.visible = tableState.columns.every(
        (item) => item.visible
      );
      // 刷新布局
      tableState.xTable.refreshColumn();
    };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableState.tableData[rowIndex].checked) {
        return {
          backgroundColor: "pink",
          // backgroundColor: 'lightblue',
          // color: '#ffffff'
        };
      }
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    // 初始化
    getPreparedData();
    handleSearch();

    // 获取所有列配置
    setTimeout(() => {
      nextTick(() => {
        tableState.columns = tableState.xTable.getColumns();
      });
    }, 100);

    // onActivated(() => {
    // });

    return {
      rowStyle,
      searchBtnLoading,
      handleSearch,
      handleReset,
      filterData,
      prepareData,
      handleCreate,
      handleEdit,
      handleStop,
      handleJoin,
      handleDelete,
      tagCheckedChange,
      getTableData,
      orgFormDialogRef,
      pagenationData,
      handleSizeChange,
      handleCurrentChange,
      ...toRefs(tableState),
    };
  },
};
</script>

<style>
.message-title {
  cursor: pointer;
}
.handle-row {
  margin-top: 30px;
}
</style>
